const { db } = require('../config/database');

class Character {
  // 创建角色
  static create(user_id, name, emoji_data, personality) {
    return new Promise((resolve, reject) => {
      const stmt = db.prepare('INSERT INTO characters (user_id, name, emoji_data, personality) VALUES (?, ?, ?, ?)');
      stmt.run(user_id, name, emoji_data, personality, function(err) {
        if (err) {
          reject(err);
        } else {
          resolve({
            id: this.lastID,
            user_id,
            name,
            emoji_data,
            personality
          });
        }
      });
      stmt.finalize();
    });
  }

  // 根据ID查找角色
  static findById(id) {
    return new Promise((resolve, reject) => {
      db.get('SELECT * FROM characters WHERE id = ?', [id], (err, row) => {
        if (err) {
          reject(err);
        } else {
          resolve(row);
        }
      });
    });
  }

  // 根据用户ID查找角色
  static findByUserId(user_id) {
    return new Promise((resolve, reject) => {
      db.all('SELECT * FROM characters WHERE user_id = ?', [user_id], (err, rows) => {
        if (err) {
          reject(err);
        } else {
          resolve(rows);
        }
      });
    });
  }

  // 更新角色
  static update(id, name, emoji_data, personality) {
    return new Promise((resolve, reject) => {
      const stmt = db.prepare('UPDATE characters SET name = ?, emoji_data = ?, personality = ? WHERE id = ?');
      stmt.run(name, emoji_data, personality, id, function(err) {
        if (err) {
          reject(err);
        } else {
          resolve({
            id,
            name,
            emoji_data,
            personality
          });
        }
      });
      stmt.finalize();
    });
  }

  // 删除角色
  static delete(id) {
    return new Promise((resolve, reject) => {
      const stmt = db.prepare('DELETE FROM characters WHERE id = ?');
      stmt.run(id, function(err) {
        if (err) {
          reject(err);
        } else {
          resolve({ id });
        }
      });
      stmt.finalize();
    });
  }
}

module.exports = Character;